import json
import paho.mqtt.client as mqtt
import sqlite3

# MQTT 服务器配置
MQTT_BROKER = '127.0.0.1'
MQTT_PORT = 1883
MQTT_TOPIC = 'iot/devices/test/baina/00000000/allinone/tx'

def get_device_addresses():
    conn = sqlite3.connect('/Users/tancongyuan/Desktop/sensor_data.db')  # 连接到数据库
    cursor = conn.cursor()
    cursor.execute("SELECT devaddr FROM parsed_sensor_info")  # 查询所有设备地址
    addresses = [row[0] for row in cursor.fetchall()]
    conn.close()
    unique_addresses = list(set(addresses))
    return addresses

# 当与服务器连接成功时被调用
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # 订阅需要监听的主题
    client.subscribe(MQTT_TOPIC)

# 当接收到来自服务器的消息时被调用
def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")

# 创建 MQTT 客户端实例
client = mqtt.Client()

# 指定连接事件和消息接收事件的回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到 MQTT 服务器
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 发送灯光控制命令
def send_light_control_command():
    devaddr_list = get_device_addresses()
    message = {
        "task_type": "set_sensor_light",
        "task_id": "194",
        "data": {
            "devaddr_list": devaddr_list,
            "value": "01"  # 红灯常亮
        }
    }
    message_json = json.dumps(message)
    client.publish(MQTT_TOPIC, message_json)
    print(f"Sent message: {message_json}")

# 发送命令示例
send_light_control_command()

# 持续运行，直到被用户中断
try:
    while True:
        pass
except KeyboardInterrupt:
    print("Exiting...")

# 停止 MQTT 客户端并断开连接
client.disconnect()